#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <stdint.h>
#include <stdio.h>
#include "driver/i2c.h"

#define I2C_MASTER_SCL_IO     3
#define I2C_MASTER_SDA_IO     10
#define I2C_MASTER_NUM        0
#define I2C_MASTER_TIMEOUT_MS 1000

/**
 * 设备地址
 *
 * bit7-bit4  固定是 1010
 * bit3-bit1  对应 A2 A1 A0
 * bit0       读写位, HIGH 读操作, LOW 写操作
 */
#define AT24C02_7BITADDR_000 0x50 // A2 = 0; A1 = 0; A0 = 0;
#define AT24C02_7BITADDR_001 0x51 // A2 = 0; A1 = 0; A0 = 1;
#define AT24C02_7BITADDR_010 0x52 // A2 = 0; A1 = 1; A0 = 0;
#define AT24C02_7BITADDR_011 0x53 // A2 = 0; A1 = 1; A0 = 1;
#define AT24C02_7BITADDR_100 0x54 // A2 = 1; A1 = 0; A0 = 0;
#define AT24C02_7BITADDR_101 0x55 // A2 = 1; A1 = 0; A0 = 1;
#define AT24C02_7BITADDR_110 0x56 // A2 = 1; A1 = 1; A0 = 0;
#define AT24C02_7BITADDR_111 0x57 // A2 = 1; A1 = 1; A0 = 1;

/**
 * 写保护
 *
 * WP = HIGH  写保护, 只能读, 不能写
 * WP = LOW   正常读写
 */
#define AT24C02_WP_PIN 2

void app_main(void)
{
	int i = 0;
	int ret = 0;
	uint8_t buf[9];
	uint8_t buf2[16];
	uint8_t addr = 0;
	int i2c_master_port = I2C_MASTER_NUM;
	i2c_config_t conf = {
		.mode = I2C_MODE_MASTER,
		.sda_io_num = I2C_MASTER_SDA_IO,
		.scl_io_num = I2C_MASTER_SCL_IO,
		.sda_pullup_en = GPIO_PULLUP_ENABLE,
		.scl_pullup_en = GPIO_PULLUP_ENABLE,
		.master.clk_speed = 400000,
	};

	gpio_reset_pin(AT24C02_WP_PIN);
	gpio_set_direction(AT24C02_WP_PIN, GPIO_MODE_OUTPUT);
	gpio_set_level(AT24C02_WP_PIN, 0);

	i2c_param_config(i2c_master_port, &conf);
	ret = i2c_driver_install(i2c_master_port, conf.mode, 0, 0, 0);
	if (ret) {
		printf("err: i2c_master_init(), ret = %d\n", ret);
	}

	buf[0] = addr;
	for (i = 1; i < 9; i++) {
		buf[i] = i + 20;
	}
	ret = i2c_master_write_to_device(I2C_MASTER_NUM, AT24C02_7BITADDR_000, buf, 9, I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);
	if (ret) {
		printf("err: i2c_master_write_to_device(), ret = %d\n", ret);
	}

	/* 这个延时很关键，后面老是写失败 */
	vTaskDelay(10 / portTICK_PERIOD_MS);

	ret = i2c_master_write_read_device(I2C_MASTER_NUM, AT24C02_7BITADDR_000, &addr, 1, buf2, 8, I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS);
	if (ret) {
		printf("err: i2c_master_write_read_device(), ret = %d\n", ret);
	}

	for (i = 0; i < 8; i++) {
		printf("0x%02x, ", buf2[i]);
	}
	printf("\n");

	while (1) {
		vTaskDelay(3000 / portTICK_PERIOD_MS);
	}
}
